<script setup>
    import axios from 'axios'
    import { ref, provide, watch, onMounted } from 'vue';
    import { useRouter, useRoute } from 'vue-router'
    import { ElMessage, ElLoading, ElMessageBox } from "element-plus";
    import { fileIco } from '../../utils'
    import request from '../../request/axios';
    import { downloadOnClick } from '../../utils/index'
    import { PATH_URL } from '../../request/axios/service.js'
    import KnowledgePopup from '../../components/knowledgePopup/index.vue'
    import FilePreview from '../../components/FilePreview/index.vue'
    import { formatDateTimeWithTimestamp } from '../../utils/time'


    const route = useRoute() // 获取路由对象
    const router = useRouter();

    const fileObj = ref({}) // 文件夹对象
    const fileAccept = ref('.pdf,.doc,.docx,.txt,.ppt,.xls,.xlsx')//上传文件类型
    const folderId = ref(route.query.folderId); // 文件夹id
    const knowledgeId = ref(route.query.knowledgeId); // 知识库id

    const deleted = ref(route.query.deleted); // 是否能删除
    const updated = ref(route.query.updated); // 是否能修改

    // 批量删除
    // 获取文件列表
    const capacity = ref('')
    const isDelSelect = ref(true) // 是否选中
    const clickDelSelectFile = async () => {
        if (!isDelSelect.value) {
            const knowledgeIds = fileList.value
                .filter(item => item.checked && item.type === 2)
                .map(item => item.id);
            const folderIds = fileList.value
                .filter(item => item.checked && item.type === 1)
                .map(item => item.id);

            const data = {
                folder_ids: folderIds.join(','),
                knowledge_file_ids: knowledgeIds.join(',')
            }
            const res = await request.postV2({ url: 'v1/api-del-files', data })
            if (res.code == 200) {
                getFileList(true);
            }
        }
        isDelSelect.value = !isDelSelect.value;
    }

    // 全选删除
    const clickDelSelectAll = async () => {
        // const type2Files = fileList.value.filter(item => item.type === 2);
        const type2Files = fileList.value;
        if (type2Files.length === 0) return; // 无文件项时不操作

        // 检查是否所有type=2的文件都已选中
        const allChecked = type2Files.every(item => item.checked);

        // 反选逻辑：全选时设为true，全选状态时设为false
        const targetChecked = !allChecked;
        type2Files.forEach(item => {
            item.checked = targetChecked; // 批量更新选中状态
        });
    }

    // 获取知识库 / 文件夹名称
    const getFileName = async () => {
        const data = {
            folder_id: folderId.value,
            knowledge_id: knowledgeId.value,
        }
        const res = await request.postV2({ url: 'v1/api-get-level', data })
        if (res.code == 200) {
            console.log('!!!!!!!----', res.data.name);
            breadcrumb.value = res.data.name;
        }
    }

    folderId.value = folderId.value == 0 ? '' : folderId.value;
    // const userInfo = ref({
    //     head: '',
    //     nickname: '',
    // })
    // const userMes = JSON.parse(localStorage.getItem('userInfo'))
    // userMes && (userInfo.value = userMes)

    const userMessage = ref(JSON.parse(localStorage.getItem('userInfo'))) // 用户信息
    const isMember = ref(0); // 是否会员
    const isCompanyMember = ref(0); // 是否企业会员
    onMounted(() => {
        isMember.value = 0
        isCompanyMember.value = 0
        if (userMessage.value?.is_member) { isMember.value = userMessage.value?.is_member }
        if (userMessage.value?.is_company_member) { isCompanyMember.value = userMessage.value?.is_company_member }
    })

    // 面包屑
    const breadcrumb = ref(localStorage.getItem('breadcrumb'))

    // popup 弹窗
    const sourceVisible = ref(false)
    const dialogVisible = ref(false)

    // 设置文件夹对象
    const setFileObj = () => {
        fileObj.value = {
            folder_id: folderId.value,
            knowledge_id: knowledgeId.value,
        }
    }
    setFileObj();

    // 获取文件列表
    const total = ref(0)
    const page = ref(1)
    const fileList = ref([]) // 文件列表
    const getFileList = async (del) => {
        try {
            const apiUrl = folderId.value == '' || folderId.value == '0' ? `/v1/api-folder-file-list?page=${page.value}&pageNum=15&knowledge_id=${knowledgeId.value}` : `/v1/api-folder-file-list?folder_id=${folderId.value}&page=${page.value}&pageNum=15`
            const res = await request.getV2({ url: apiUrl });
            breadcrumb.value =res.data.level; //取这个接口的level
            fileList.value = res.data.length == 0 ? [] : res.data.list;
            capacity.value = res.data.capacity
            total.value = res.data.length == 0 ? 0 : res.data.pageInfo.count
            collectionLoading.value = false; // 隐藏加载中
            if (del) return ElMessage.success("删除成功");
        } catch (error) {
            console.log(error);
        }
    }

    const changeKnowledge = (val) => {
        page.value = val;
        getFileList()
    }

    // 组件增删改 重新获取文件列表
    provide('fileMessage', value => {
        getFileList()
    })

    // 新建文件夹
    const popupType = ref('0')// 3 新增文件夹 4 编辑文件夹 5 删除文件夹
    const knowledgePopupRef = ref(null);
    const addFilePopup = (type) => {
        popupType.value = type;
        fileObj.value = {
            folder_id: folderId.value,
            knowledge_id: knowledgeId.value,
        }
        if (knowledgePopupRef.value) return knowledgePopupRef.value.setPopupBox();
    }
    // 编辑文件夹
    const clickEditFile = (row) => {
        popupType.value = '4'
        fileObj.value = row
        if (knowledgePopupRef.value) return knowledgePopupRef.value.setEditPopupBox(row);
    }
    // 删除文件夹 / 文件
    const clickDelFile = async (row) => {
        // popupType.value = '5'
        // fileObj.value = row
        // if (knowledgePopupRef.value) return knowledgePopupRef.value.setPopupBox();
        try {
            const data = {}
            const apiUrl = row.type == 1 ? '/v1/api-folder-del' : '/v1/api-del-file'
            const loading = ElLoading.service({
                lock: true,
                text: '加载中...',
            })
            if (row.type == 1) {
                data.folder_id = row.id
            } else {
                data.knowledge_file_id = row.id
            }
            const res = await request.postV2({ url: apiUrl, data })
            loading.close()
            if (res.code == 200) {
                getFileList(true);
            }
        } catch (error) {
            console.log(error)
        }
    }

    // 监听路由参数变化
    watch(
        () => route.query.folderId,
        (newId, oldId) => {
            if (newId !== oldId) {
                folderId.value = newId
                breadcrumb.value = localStorage.getItem('breadcrumb')
                setFileObj()
            }
            getFileList();
            // getFileName()
        },
        { immediate: true }
    )

    // 文件上传
    const collectionLoading = ref(false)
    const filePopupShow = ref(false)
    const handleUpload = async (file) => {
        const url = PATH_URL + '/v1/api-upload-oss'
        const formData = new FormData()
        folderId.value != '0' ? formData.append('folder_id', folderId.value) : formData.append('knowledge_id', knowledgeId.value)
        formData.append('file[]', file.file, file.name)
        // 添加一个加载中的loding用于显示上传进度
        dialogVisible.value = false; // 关闭弹窗
        collectionLoading.value = true; // 显示加载中
        axios
            .post(url, formData, {
                headers: {
                    'Authorization': localStorage.getItem("token") || '',
                    'Content-Type': 'multipart/form-data'
                }
            })
            .then((response) => {
                getFileList();
                if (response.data.code == 201 && !filePopupShow.value) {
                    filePopupShow.value = true;
                    ElMessageBox.confirm(response.data.msg, {
                        confirmButtonText: '去购买',
                        cancelButtonText: '取消',
                    })
                        .then(() => {
                            window.open(response.data.data.url, '_blank');
                        })
                        .catch(() => {
                            console.log('关闭');
                            return;
                        })
                    return
                }
                // if (response.data.code != 200 ||) return ElMessage.error(response.data.msg)
            })
            .catch((error) => {
                getFileList();
                console.log('Upload error:', error)
            })
    }
    const drawerVisible = ref(false);
    const selectedFile = ref(null);

    const clickRepository = (row) => {
        if (row.type == 1) {
            return router.push(`/fileList?knowledgeId=${knowledgeId.value}&folderId=${row.id}`);
        }

        // 如果是文件，打开预览抽屉
        selectedFile.value = row;
        drawerVisible.value = true;
    }

    const closeDrawer = () => {
        drawerVisible.value = false;
    }

    // 下载文件
    const downloadFile = () => {
        if (selectedFile.value && selectedFile.value.oss_url) {
            downloadOnClick(selectedFile.value.oss_url);
        }
    }

    // 文件提示信息
    const setTipsText = (item) => {
        if (item.type == 1) return item.content || '暂无描述';
        return item.status == 1 ? '正在解析中~' : '已解析';
    }
    // 初始化icon
    const formattingIcon = (name) => {
        if (!name) return
        return fileIco(name)
    }
    const fileIcon = (name) => {
        const icon = formattingIcon(name)
        const image = new URL(`../../assets/image/file-ico/ico-${icon}.png`, import.meta.url).href
        return image
    }

    const clickAddFilePopup = (val) => {
        fileAccept.value = val
        filePopupShow.value = false;
        sourceVisible.value = false
        dialogVisible.value = true
    }


    const clickLeft = () => {
        router.go(-1)
    }

</script>

<template>
    <div class="content-repository">
        <div class="collection-title">
            <div style="display: flex;align-items: center;">
                <el-icon style="margin-right: 4px;" @click="clickLeft">
                    <ArrowLeftBold />
                </el-icon><span>{{breadcrumb}}</span>
            </div>
            <div class="head-right">
                <!-- <div class="input-box">
                    <el-input v-model="input" class="input" type="text" placeholder="搜索文件夹" />
                    <el-button class="sel-icon">
                        <img src="../../assets/image/icon/query.png" />
                    </el-button>
                </div> -->
                <div class="tips-text">{{capacity}}</div>
                <el-button v-if="!isDelSelect" @click="clickDelSelectAll">全选</el-button>
                <el-button @click="clickDelSelectFile" :type="isDelSelect?'primary':'danger'"
                    class="sel-icon">{{isDelSelect?'管理':'删除'}}</el-button>
                <div style="position: relative;margin-left: 20px;" v-if="isMember != 0 || isCompanyMember != 0">
                    <el-dropdown>
                        <el-button class="add-repository" :icon="CirclePlus">新建</el-button>
                        <template #dropdown>
                            <el-dropdown-menu style="width: 160px;">
                                <!-- <el-upload style="width: 160px;" action="#" :show-file-list="false"
                                    :http-request="handleUpload" accept=".pdf,.doc,.docx,.txt"> -->
                                <el-dropdown-item @click="() => sourceVisible = true">
                                    <img class="w-22-r4"
                                        src="../../assets/image/file-ico/ico-default.png" />上传文件&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-dropdown-item>
                                <!-- </el-upload> -->
                                <el-dropdown-item @click="addFilePopup('3')"><img class="w-28-r4"
                                        src="../../assets/image/icon/collection-file.png" />新建文件夹</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
            </div>
        </div>
        <div class="collection-list overflow-none">
            <div v-for="(item,index) in fileList" :key="i" class="collection-item" @click="() => clickRepository(item)">
                <div class="item-title">
                    <el-checkbox v-if="!isDelSelect" v-model="item.checked" style="margin-right: 4px;" @click.stop />
                    <img v-if="item.type == 1" class="w-28-r4" src="../../assets/image/icon/collection-file.png" />
                    <img v-if="item.type == 2" :src="fileIcon(item.name)" class="w-28-r4" style="width: 20px;">
                    <div style="text-align:left;flex:1;" class="nowrap-hide">{{item.name}}</div>
                    <img class="w-20" @click.stop="clickEditFile(item)" style="margin-right: 4px;"
                        v-if="item.type == 1 && updated == 1" src="../../assets/image/icon/collection-updata.png" />
                    <!-- <img class="w-20" @click.stop="clickDelFile(item)"
                        src="../../assets/image/icon/collection-del.png" /> -->
                    <el-popover placement="top" :width="160">
                        <template #reference>
                            <img class=" w-20" v-if="deleted == 1" src="../../assets/image/icon/collection-del.png" />
                        </template>
                        <div class="popover-content">
                            <span>确定删除该知识库？</span>
                            <el-button @click="clickDelFile(item)" size="small" class="popover-btn"
                                type="primary">确定</el-button>
                        </div>
                    </el-popover>
                </div>
                <div class="item-tips nowrap-hide-2">{{setTipsText(item)}}</div>
                <div class="item-bottom">
                    <div style="display: flex;align-items: center;">
                        <!-- <img class="w-20" v-if="userInfo.head = ''" :src="userInfo.head" />
                        {{userInfo.nickname || '--'}} -->
                    </div>
                    <span class="item-time">{{formatDateTimeWithTimestamp(item.create_time)}}</span>
                </div>
            </div>
            <div class="collection-item" v-if="collectionLoading" v-loading="collectionLoading"></div>
            <div class="pagination-content" v-if="total > 16">
                <el-pagination background layout="prev, pager, next" @current-change="changeKnowledge" :total="total"
                    :page-size="16" />
            </div>
        </div>
        <el-empty :image-size="200" description="暂无数据" v-if="fileList.length === 0" />
        <KnowledgePopup :popupType="popupType" :fileObj="fileObj" :kId="knowledgeId.value" ref="knowledgePopupRef" />
        <!-- 上传文件弹窗 -->
        <el-dialog v-model="sourceVisible" title="选择来源" width="600">
            <div class="source-item" @click="clickAddFilePopup('.pdf,.docx,.txt,.pptx')">
                <div class="source-title">本地文件</div>
                <div class="source-tips">上传 PDF、TXT、DOCX、PPTX 等格式的文件</div>
            </div>
            <div class="source-item" @click="clickAddFilePopup('.xls,.xlsx')">
                <div class="source-title">本地文件</div>
                <div class="source-tips">上传 XLS、XLSX 等格式的文件</div>
            </div>
        </el-dialog>
        <!-- 拖拽上传文件 -->
        <el-dialog v-model="dialogVisible" title="文件上传" width="600">
            <el-upload class="upload-demo" drag multiple action="#" :show-file-list="false" :http-request="handleUpload"
                :accept="fileAccept">
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                    点击或拖动文件到此处上传
                </div>
            </el-upload>
        </el-dialog>

        <!-- 文件预览抽屉 -->
        <el-drawer v-model="drawerVisible" :title="selectedFile?.name || '文件预览'" direction="rtl" size="50%"
            :destroy-on-close="false" :before-close="closeDrawer" custom-class="file-preview-drawer">
            <template #header>
                <div class="drawer-header">
                    <span>{{ selectedFile?.name || '文件预览' }}</span>
                    <div class="drawer-actions">
                        <el-button type="primary" size="small" @click="downloadFile">
                            <el-icon>
                                <download />
                            </el-icon>下载
                        </el-button>
                    </div>
                </div>
            </template>
            <FilePreview :file="selectedFile" :visible="drawerVisible" />
        </el-drawer>
    </div>
</template>

<style scoped lang="scss">
    .tips-text {
        font-size: 14px;
        color: #666666;
        font-weight: 500;
        margin-right: 20px;
    }

    :deep(.file-preview-drawer) {
        .el-drawer__body {
            padding: 0;
            overflow: hidden;
        }
    }

    .drawer-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;

        span {
            font-size: 16px;
            font-weight: bold;
            color: #333;
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .drawer-actions {
            display: flex;
            gap: 8px;
        }
    }

    .popover-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;

        span {
            font-size: 14px;
            color: #666666;
        }

        .popover-btn {
            width: 80%;
            margin-top: 6px;
        }
    }

    .source-item {
        cursor: pointer;
        padding: 10px 20px;
        border-radius: 12px;
        margin-bottom: 20px;
        box-shadow: 0px 0px 7px 0px rgba(0, 0, 0, 0.08);
        border: 1px solid #F0F4FF;
    }

    .pagination-content {
        display: flex;
        width: 100%;
        align-items: center;
        justify-content: end;
        margin-top: 10px;
    }

    .w-28-r4 {
        width: 28px;
        margin-right: 4px;
    }

    .w-20 {
        width: 20px;
    }

    .w-22-r4 {
        width: 22px;
        margin-right: 4px;
    }

    .content-repository {
        width: 1000px;
        overflow: hidden;
        overflow-y: auto;
        padding: 50px 0;

        .collection-title {
            font-size: 20px;
            font-weight: bold;
            color: #000000;
            margin-bottom: 18px;
            padding: 0 12px;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .head-right {
                display: flex;
                align-items: center;

                .input-box {
                    width: 550px;
                    height: 50px;
                    overflow: hidden;
                    border-radius: 73px;
                    background: #FFFFFF;
                    position: relative;

                    &::after {
                        content: '';
                        width: 2px;
                        height: 50px;
                        background: #fff;
                        position: absolute;
                        right: 82px;
                        top: 0px;
                    }

                    .input {
                        width: 470px;
                        height: 54px;
                        margin-left: -2px;
                        margin-top: -2px;
                    }

                    .sel-icon {
                        width: 70px;
                        height: 40px;
                        background: #2D66B3;
                        position: absolute;
                        z-index: 999;
                        right: 5px;
                        top: 5px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        border-radius: 73px;

                        img {
                            width: 20px;
                            height: 20px;
                        }
                    }
                }

                .add-repository {
                    width: 90px;
                    height: 40px;
                    color: #fff;
                    font-size: 16px;
                    border-radius: 8px;
                    background: #2D66B3;

                }
            }
        }

        .collection-list {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            justify-content: flex-start;

            .collection-item {
                width: calc(100% / 3 - 26px);
                /* width: 363px; */
                overflow: hidden;
                height: 120px;
                overflow: hidden;
                margin: 0 7px 14px;
                border-radius: 8px;
                background: #FFFFFF;
                padding: 6px;
                cursor: pointer;
                box-shadow: 0px 0px 7px 0px rgba(0, 0, 0, 0.08);

                .item-title {
                    font-size: 15px;
                    padding: 0 10px 0 6px;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                }

                .item-tips {
                    font-size: 14px;
                    color: #666;
                    line-height: 24px;
                    margin: 10px;
                    min-height: 50px;
                }

                .item-bottom {
                    display: flex;
                    align-content: inherit;
                    justify-content: space-between;
                    font-size: 13px;
                    padding: 0 10px;
                    color: rgba(153, 153, 153, 0.7);

                    img {
                        width: 20px;
                        height: 20px;
                        margin-right: 10px;
                        border-radius: 50%;
                        background-color: #eee;
                    }
                }
            }
        }
    }
</style>